<script setup lang="ts">
import { computed, type Ref } from "vue";
import { storeToRefs } from "pinia";
import { onBeforeRouteUpdate, useRoute } from "vue-router";
import type { RouteLocationNormalized } from "vue-router";
import type { Banner, Category } from "@/types/homeTypes/homeTypes.ts";
import type { TopCategory } from "@/types/categoryTypes/categoryTypes.ts";
import useHomeStore from "@/pinia/modules/homeStore/homeStore.ts";
import useCategoryStore from "@/pinia/modules/categoryStore/categoryStore.ts";
import Carousel from "@/components/lib/Carousel.vue";
import SubList from "@/views/category/components/subList/subList.vue";
import GoodList from "@/views/category/components/goodList/goodList.vue";

const route: RouteLocationNormalized = useRoute();
const homeStore = useHomeStore();
const categoryStore = useCategoryStore();

const { bannerList }: { bannerList: Ref<Banner[]> } = storeToRefs(homeStore);

const { topCategoryList }: { topCategoryList: Ref<TopCategory> } = storeToRefs(categoryStore);


/*根据路由参数计算出当前分类*/
const category = computed<Category | undefined>(() => homeStore.categoryList.find(cate => cate?.id === route.params.id as string));
/*当前分类的ID*/
const categoryId = computed<string | undefined>(() => category.value?.id);


/*调用函数获取轮播图*/
homeStore.fetchBannerList();

/*调用函数获取一级类目*/
categoryStore.fetchTopCategory(route.params.id as string);

onBeforeRouteUpdate((to, from, next) => {
   // 放行
   next();
   /*再次调用函数获取一级类目*/
   categoryStore.fetchTopCategory(to.params.id as string);
});
</script>

<template>
   <div class="category container">
      <!--面包屑-->
      <breadcrumb>
         <breadcrumb-item to="/">首页</breadcrumb-item>
         <transition name="slide-fade" mode="out-in">
            <breadcrumb-item :key="categoryId">{{ category?.name }}</breadcrumb-item>
         </transition>
      </breadcrumb>
      <!--轮播图-->
      <Carousel :banner-list="bannerList" :interval="3000" :auto-play="true"></Carousel>
      <!--分类列表-->
      <sub-list :children="category?.children"></sub-list>
      <!--商品列表-->
      <good-list :children="topCategoryList?.children"></good-list>
   </div>
</template>

<style scoped lang="less">
.category {
   :deep(.carousel) {
      width: 100%;
      height: 500px;
   }
}
</style>
